<template>
  <div class="webchatLabel">
    <div class="warn-text"><span class="el-icon-info"></span>
      会话标签上限为1000个；编辑标签名称，会话记录中的标签也会变更；标签支持停用/启用
    </div>
    <div class="funBox">
      <el-input class="search" placeholder="请输入关键字" prefix-icon="el-icon-search" v-model="searchKey" @input="iptChange"></el-input>
      <span>标签：</span>
      <el-select v-model="selectValue" filterable placeholder="请选择" @change="selectChange">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <div class="fr">
        <el-button @click="handleImport" size="mini" class="importBtn">导入</el-button>
        <el-button type="primary" size="mini" @click="handleExport">导出</el-button>
      </div>
    </div>
    <labelTree
      ref="labelTree"
      @delFun="delFun"
      @openOrStopFun="openOrStopFun"
      @addLabel="addLabel"
      @editLabel="editLabel"
      class="labelTree"
      :treeData="propTreeData"
      :importType="'webchat'">
    </labelTree>
    <el-dialog
      title="导入会话标签"
      :visible.sync="dialogVisible"
      width="586px">
      <div class="warn-text"><span class="el-icon-info"></span>
        同级标签不可以重名；请勿随意修改导入模板；标签条数超过限制后超过部分将导入失败
      </div>
      <div class="content">
        <span class="title"><span class="number">1</span>第一步：</span>请按照模板格式准备需要导入的数据
        <a class="btn" style="marginBottom:25px" href="/temp/webchatLabel.xlsx" download="webchatLabel-import">
          <span class="V7_iconfont V7_iconV7tubiao_xianxiazai"></span>
          下载导入模版
        </a>
        <span class="title"><span class="number">2</span>第二步：</span>选择需要导入的文件（支持xls、xlsx文件，单个文件不得大于10M）
        <el-upload
          class="upload-demo"
          ref="epxortLabel"
          accept=".xls, .xlsx"
          :action="webchatLabelUrl"
          :limit='1'
          :on-success="handleImportSuccess"
          :on-remove="handleRemove"
          :headers="{
            sessionid: accountObj.userId,
            loginToken: accountObj.loginToken
          }">
          <div class="btn">
            <span class="V7_iconfont V7_iconV7tubiao_zaixian-wenjian"></span>
            选择文件
          </div>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini">取消</el-button>
        <el-button type="primary" @click="importSave" size="mini">导入</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import labelTree from '@/components/labelTree/index.vue'
import { BasicModule } from '@/store/modules/config/basic'
import { deepClone } from '@/utils/common'
function hanleSearchdata (data: any, serachKey: string, selectValue: string) {
  const array: any = []
  for (let i = 0; i < data.length; i++) {
    if (data[i].children && data[i].children.length > 0) {
      data[i].children = hanleSearchdata(data[i].children, serachKey, selectValue)
    }
    if (selectValue === 'open') {
      // eslint-disable-next-line no-mixed-operators
      if (data[i].name.indexOf(serachKey) > -1 && data[i].isEnabled || (data[i].children && data[i].children.length > 0)) {
        array.push(data[i])
      }
    } else if (selectValue === 'stop') {
      // eslint-disable-next-line no-mixed-operators
      if (data[i].name.indexOf(serachKey) > -1 && !data[i].isEnabled || (data[i].children && data[i].children.length > 0)) {
        array.push(data[i])
      }
    } else {
      if (data[i].name.indexOf(serachKey) > -1 || (data[i].children && data[i].children.length > 0)) {
        array.push(data[i])
      }
    }
  }
  return array
}
@Component({
  name: 'webchatLabel',
  components: { labelTree }
})
export default class WebchatLabel extends Vue {
  @Ref() private readonly labelTreeRef !: labelTree
  private $message: any
  private $router: any
  private $updateCache: any
  private $store: any

  private searchKey: string = ''

  private fileObj: any = {
    path: ''
  }

  private selectValue: string = ''

  private dialogVisible: boolean = false

  private options = [
    { label: '全部', value: '' },
    { label: '启用', value: 'open' },
    { label: '停用', value: 'stop' }
  ]

  private searchTreeData = [] // 搜索的树结构

  private propTreeData = [] // 传递的树结构

  private accountObj = {
    account: '',
    userId: '',
    loginToken: ''
  }

  private treeData = [] // 数据库树结构

  get webchatLabelUrl () {
    return '/upload?accountId=' + this.accountObj.account + '&module=label'
  }

  private importSave () {
    if (!this.fileObj.path) {
      this.$message.error('请选择文件上传')
      return
    }
    const actionData = {
      url: '/im-center/action/config/tag/importTask',
      method: 'post',
      data: {
        filepath: this.fileObj.path
      }
    }
    const epxortRef: any = this.$refs.epxortLabel
    epxortRef.clearFiles()
    BasicModule.BasicCommonAction(actionData).then(res => {
      if (res && res.success) {
        this.$message.success('导入任务已经生成，请前往传输中心查看！')
        this.dialogVisible = false
        this.fileObj.path = ''
      }
    })
  }

  private handleRemove () {
    this.fileObj.path = ''
  }

  private jumpToTransmissionCenter () {
    this.$router.push('/transmission_center/index/tx_export_task?taskModule=sessionTags')
  }

  private getTreeData (add?: any) { // 获取标签树数据
    const actionData = { url: '/im-center/action/config/tag/list', method: 'POST', data: {} }
    BasicModule.BasicCommonAction(actionData).then(res => {
      if (res && res.success && res.data.tree) {
        this.treeData = res.data.tree || []
        this.searchTreeData = deepClone(this.treeData)
        this.propTreeData = deepClone(hanleSearchdata(this.searchTreeData, this.searchKey, this.selectValue))
      }
    })
  }

  private addLabel (obj: any) { // 添加标签
    const treeRef: any = this.$refs.labelTree
    const { color, parentId, name } = obj
    if (!name) {
      this.$message.error('标签名字不能为空')
      return
    }
    const sendData = {
      color,
      parentId,
      name
    }
    const actionData = { url: '/im-center/action/config/tag/create', method: 'POST', data: sendData }
    BasicModule.BasicCommonAction(actionData).then(res => {
      if (res && res.success) {
        treeRef.addSuccessFun(obj)
        this.$message.success('添加标签成功')
        this.getTreeData()
      }
    })
  }

  private editLabel (obj: any, type: string) { // 编辑标签
    const treeRef: any = this.$refs.labelTree
    const { color, _id, label } = obj
    if (!type && !label) {
      this.$message.error('标签名字不能为空')
      return
    }
    const sendData = {
      color,
      _id,
      name: label || ''
    }
    if (type === 'color') {
      delete sendData.name
    }
    obj.success = false
    const actionData = { url: '/im-center/action/config/tag/update', method: 'POST', data: sendData }
    BasicModule.BasicCommonAction(actionData).then(res => {
      if (res && res.success) {
        obj.success = true
        this.$message.success(`${type && type === 'color' ? '更改颜色' : '编辑标签'}成功`)
      }
      treeRef.editSuccessFun(obj)
    })
  }

  private openOrStopFun (obj: any) {
    const sendData = {
      _id: obj._id,
      isEnabled: !obj.isEnabled
    }
    const actionData = { url: '/im-center/action/config/tag/updateIsEnabled', method: 'POST', data: sendData }
    BasicModule.BasicCommonAction(actionData).then(res => {
      if (res && res.success) {
        this.$message.success(`${obj.isEnabled ? '停用' : '启用'}标签成功`)
        this.getTreeData()
      }
    })
  }

  private delFun (obj: any) { // 删除
    const sendData = {
      _id: obj._id
    }
    const actionData = { url: '/im-center/action/config/tag/delete', method: 'POST', data: sendData }
    BasicModule.BasicCommonAction(actionData).then(res => {
      if (res && res.success) {
        this.$message.success('删除标签成功')
        this.getTreeData()
      }
    })
  }

  private iptChange () {
    this.searchTreeData = deepClone(this.treeData)
    if (this.searchKey) {
      this.propTreeData = deepClone(hanleSearchdata(this.searchTreeData, this.searchKey, this.selectValue))
    } else {
      this.propTreeData = deepClone(this.treeData)
      this.selectChange()
    }
  }

  private selectChange () {
    this.searchTreeData = deepClone(this.treeData)
    if (this.selectValue) {
      this.propTreeData = deepClone(hanleSearchdata(this.searchTreeData, this.searchKey, this.selectValue))
    } else {
      this.propTreeData = deepClone(this.treeData)
    }
  }

  private handleImport () { // 导入
    this.dialogVisible = true
  }

  private handleImportSuccess (res: any) {
    if (res && res.success) {
      this.fileObj.path = res.data.path
    }
  }

  private handleExport () { // 导出
    const actionData = {
      url: '/im-center/action/config/tag/exportTask',
      method: 'post',
      data: {}
    }
    BasicModule.BasicCommonAction(actionData).then(res => {
      if (res && res.success) {
        const h = this.$createElement
        this.$message({
          message: h('div', { style: 'color:#2ed47a' }, [
            h('span', {}, `导出任务${res.data.taskId || ''}进入排队，请前往`),
            h('a', { on: { click: this.jumpToTransmissionCenter }, style: 'cursor:pointer,color:#008cee' }, '传输中心'),
            h('span', {}, '查看')
          ]),
          type: 'success',
          duration: 5000
        })
      }
    })
  }

  private mounted () {
    this.getTreeData()
    this.accountObj.account = this.$store.state.common.session.account._id
    this.accountObj.userId = this.$store.state.common.session.user._id
    this.accountObj.loginToken = this.$store.state.common.session.user.loginToken
  }
}
</script>
<style scoped lang="stylus">
  .webchatLabel
    padding 16px
    border-radius 10px
    height calc(100% - 40px)
    overflow auto
    box-sizing border-box
    margin 0 2px 2px 0
    border 1px solid #ecf0f3
    box-shadow 0px 0px 4px 0px #e0e6f0, 0px 1px 4px 0px #e0e6f0
    .warn-text
      background $bgc-reminder
      padding 14px
      margin-bottom 20px
      border-radius 4px
      font-size 12px
      .el-icon-info
        color $c-warn
        padding-right 6px
        font-size 14px
        vertical-align middle
    .funBox
      border-bottom 1px solid $border-main
      padding-bottom 16px
      .search
        width 500px
        margin-right 20px
    .labelTree
      height calc(100% - 130px)
    .content
      font-size 12px
      .title
        color #303753
        font-weight 600
    .btn
      display block
      width 160px
      height 30px
      line-height 30px
      text-align center
      font-size 12px
      color #303854
      background #FFFFFF
      border 1px solid #ECF0F3
      border-radius 4px
      margin-top 11px
      cursor pointer
      .V7_iconfont
        color #B3B9C7
        vertical-align middle
        margin-right 6px
        font-size 12px
    .btn:hover
      color #008BEE
      background #F3FAFF
      border 1px solid #008BEE
    .btn:hover .V7_iconfont
        color #008BEE
    .number
      width 14px
      height 14px
      display inline-block
      background #008BEE
      text-align center
      border-radius 50%
      line-height 14px
      color #fff
      margin-right 6px
</style>
